package com.liliudong.template.common.listener;

import com.liliudong.template.common.entity.BaseEntity;
import com.liliudong.template.common.security.util.SecurityUtil;
import com.mybatisflex.annotation.InsertListener;
import com.mybatisflex.annotation.UpdateListener;

import java.time.LocalDateTime;

/**
 * 基础的数据填充监听器
 *
 * @author liudo
 * @version 1.0
 * @project template-backend
 * @date 2024/8/1 08:34:19
 */
public class BaseFieldFillListener implements InsertListener, UpdateListener {

    @Override
    public void onInsert(Object o) {
        BaseEntity entity = (BaseEntity) o;

        long loginUserId = SecurityUtil.getLoginUserId();
        String deptNo = SecurityUtil.getDeptNo();
        LocalDateTime now = LocalDateTime.now();
        entity.setCreatedAt(now);
        entity.setCreatedBy(loginUserId);
        entity.setCreatedFrom(deptNo);
        entity.setUpdatedAt(now);
        entity.setUpdatedBy(loginUserId);
        entity.setDeleted(0);
    }

    @Override
    public void onUpdate(Object o) {
        BaseEntity entity = (BaseEntity) o;

        long loginUserId = SecurityUtil.getLoginUserId();
        LocalDateTime now = LocalDateTime.now();
        entity.setUpdatedAt(now);
        entity.setUpdatedBy(loginUserId);
        entity.setDeleted(0);
    }
}
